package cn.harry.cabinet.view

import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.lifecycleScope
import cn.harry.cabinet.R
import cn.harry.cabinet.databinding.ActivitySystemConfigBinding
import cn.harry.cabinet.theme.manager.ButtonThemeManager
import cn.harry.cabinet.theme.manager.NavigationThemeManager
import cn.harry.cabinet.theme.manager.ThemeManager
import cn.harry.cabinet.theme.updater.DynamicThemeUpdater
import cn.harry.cabinet.view.fragments.CardManagementFragment
import cn.harry.cabinet.view.fragments.FaceRecognitionFragment
import cn.harry.cabinet.view.fragments.FeatureLibraryFragment
import cn.harry.cabinet.view.fragments.HomeConfigFragment
import cn.harry.cabinet.view.fragments.NetworkConfigFragment
import cn.harry.cabinet.view.fragments.OperationLogFragment
import cn.harry.cabinet.view.fragments.PasswordManagementFragment
import cn.harry.cabinet.view.fragments.ProgramManagementFragment
import cn.harry.cabinet.view.fragments.SerialConfigFragment
import cn.harry.cabinet.view.fragments.UsageRecordFragment
import cn.harry.cabinet.view.fragments.UserManagementFragment
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class SystemConfigActivity : AppCompatActivity() {
    
    private lateinit var binding: ActivitySystemConfigBinding
    
    // 是否显示迷你导航栏（仅图标模式）
    private var isMiniNavMode = false
    
    // 菜单项ID与标题的映射关系
    private val menuTitleMap = mapOf(
        R.id.nav_home_config to "首页配置",
        R.id.nav_network_config to "网络配置", 
        R.id.nav_serial_config to "串口配置",
        R.id.nav_face_recognition to "人脸识别",
        R.id.nav_feature_library to "特征库管理",
        R.id.nav_password_management to "密码管理",
        R.id.nav_user_management to "用户管理",
        R.id.nav_card_management to "刷卡管理",
        R.id.nav_operation_log to "操作日志",
        R.id.nav_usage_record to "使用记录",
        R.id.nav_program_management to "程序管理"
    )
    
    // 菜单项ID与图标的映射关系
    private val menuIconMap = mapOf(
        R.id.nav_home_config to R.drawable.ic_homepage,
        R.id.nav_network_config to R.drawable.ic_network,
        R.id.nav_serial_config to R.drawable.ic_serial,
        R.id.nav_face_recognition to R.drawable.ic_face,
        R.id.nav_feature_library to R.drawable.ic_library,
        R.id.nav_password_management to R.drawable.ic_password,
        R.id.nav_user_management to R.drawable.ic_user,
        R.id.nav_card_management to R.drawable.ic_card,
        R.id.nav_operation_log to R.drawable.ic_log,
        R.id.nav_usage_record to R.drawable.ic_record,
        R.id.nav_program_management to R.drawable.ic_program
    )
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        binding = ActivitySystemConfigBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        setupToolbar()
        setupNavigationMenu()
        setupDrawerLayout()
        setupBackToHomeButton()
        
        // 应用保存的主题（在binding初始化后）
        applyTheme()
        
        // 默认显示页面
        showFragment(HomeConfigFragment())
        // 设置默认标题和选中状态
        updateToolbarTitle(R.id.nav_home_config)
        binding.navigationView.setCheckedItem(R.id.nav_home_config)
        
        // 默认显示迷你导航栏
        isMiniNavMode = true
        showMiniNavigationBar(R.id.nav_home_config)
    }
    
    private fun setupToolbar() {
        setSupportActionBar(binding.toolbar)
        supportActionBar?.apply {
            setDisplayHomeAsUpEnabled(true)
            setHomeAsUpIndicator(R.drawable.ic_menu) // 设置汉堡菜单图标
            title = "系统配置"
        }
        
        // 确保导航图标（汉堡菜单）为白色
        binding.toolbar.navigationIcon?.let { navIcon ->
            navIcon.setTint(ContextCompat.getColor(this, R.color.white))
        }
    }
    
    /**
     * 根据菜单项ID更新工具栏标题
     */
    private fun updateToolbarTitle(menuItemId: Int) {
        val title = menuTitleMap[menuItemId] ?: "系统配置"
        supportActionBar?.title = title
    }
    
    /**
     * 更新工具栏图标颜色，确保图标为白色
     */
    private fun updateToolbarIconColor() {
        binding.toolbar.navigationIcon?.let { navIcon ->
            navIcon.setTint(ContextCompat.getColor(this, R.color.white))
        }
        binding.toolbar.overflowIcon?.let { overflowIcon ->
            overflowIcon.setTint(ContextCompat.getColor(this, R.color.white))
        }
    }
    
    /**
     * 公共方法：强制更新工具栏图标颜色
     * 供Fragment或其他组件在主题切换后调用
     */
    fun forceUpdateToolbarIconColor() {
        updateToolbarIconColor()
    }
    
    private fun setupNavigationMenu() {
        // 设置导航菜单点击事件
        binding.navigationView.setNavigationItemSelectedListener { menuItem ->
            when (menuItem.itemId) {
                R.id.nav_home_config -> {
                    showFragment(HomeConfigFragment())
                    updateToolbarTitle(R.id.nav_home_config)
                    menuItem.isChecked = true
                    switchToMiniNavMode(R.id.nav_home_config)
                    true
                }
                R.id.nav_network_config -> {
                    showFragment(NetworkConfigFragment())
                    updateToolbarTitle(R.id.nav_network_config)
                    menuItem.isChecked = true
                    switchToMiniNavMode(R.id.nav_network_config)
                    true
                }
                R.id.nav_serial_config -> {
                    showFragment(SerialConfigFragment())
                    updateToolbarTitle(R.id.nav_serial_config)
                    menuItem.isChecked = true
                    switchToMiniNavMode(R.id.nav_serial_config)
                    true
                }
                R.id.nav_face_recognition -> {
                    showFragment(FaceRecognitionFragment())
                    updateToolbarTitle(R.id.nav_face_recognition)
                    menuItem.isChecked = true
                    switchToMiniNavMode(R.id.nav_face_recognition)
                    true
                }
                R.id.nav_feature_library -> {
                    showFragment(FeatureLibraryFragment())
                    updateToolbarTitle(R.id.nav_feature_library)
                    menuItem.isChecked = true
                    switchToMiniNavMode(R.id.nav_feature_library)
                    true
                }
                R.id.nav_password_management -> {
                    showFragment(PasswordManagementFragment())
                    updateToolbarTitle(R.id.nav_password_management)
                    menuItem.isChecked = true
                    switchToMiniNavMode(R.id.nav_password_management)
                    true
                }
                R.id.nav_user_management -> {
                    showFragment(UserManagementFragment())
                    updateToolbarTitle(R.id.nav_user_management)
                    menuItem.isChecked = true
                    switchToMiniNavMode(R.id.nav_user_management)
                    true
                }
                R.id.nav_card_management -> {
                    showFragment(CardManagementFragment())
                    updateToolbarTitle(R.id.nav_card_management)
                    menuItem.isChecked = true
                    switchToMiniNavMode(R.id.nav_card_management)
                    true
                }
                R.id.nav_operation_log -> {
                    showFragment(OperationLogFragment())
                    updateToolbarTitle(R.id.nav_operation_log)
                    menuItem.isChecked = true
                    switchToMiniNavMode(R.id.nav_operation_log)
                    true
                }
                R.id.nav_usage_record -> {
                    showFragment(UsageRecordFragment())
                    updateToolbarTitle(R.id.nav_usage_record)
                    menuItem.isChecked = true
                    switchToMiniNavMode(R.id.nav_usage_record)
                    true
                }
                R.id.nav_program_management -> {
                    showFragment(ProgramManagementFragment())
                    updateToolbarTitle(R.id.nav_program_management)
                    menuItem.isChecked = true
                    switchToMiniNavMode(R.id.nav_program_management)
                    true
                }
                else -> false
            }
        }
    }
    
    private fun setupDrawerLayout() {
        // 设置抽屉式导航的监听器
        binding.drawerLayout.addDrawerListener(object : androidx.drawerlayout.widget.DrawerLayout.DrawerListener {
            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
                // 抽屉滑动时的回调
            }
            
            override fun onDrawerOpened(drawerView: View) {
                // 抽屉打开时的回调
            }
            
            override fun onDrawerClosed(drawerView: View) {
                // 抽屉关闭时的回调
            }
            
            override fun onDrawerStateChanged(newState: Int) {
                // 抽屉状态改变时的回调
            }
        })
    }
    
    private fun setupBackToHomeButton() {
        // 设置返回首页按钮的点击事件
        binding.backToHomeButton.setOnClickListener {
            // 关闭导航菜单
            binding.drawerLayout.closeDrawer(binding.navigationContainer)
            
            // 返回MainActivity
            finish()
        }
    }
    
    private fun showFragment(fragment: Fragment) {
        val fragmentManager: FragmentManager = supportFragmentManager
        val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
        
        // 替换右侧内容区域
        fragmentTransaction.replace(R.id.content_frame, fragment)
        fragmentTransaction.commit()
        
        // 等待Fragment视图创建完成后应用主题
        fragmentManager.executePendingTransactions()
        
        // 延迟应用主题，确保Fragment的视图已经完全创建
        binding.root.post {
            applyThemeToCurrentFragment()
        }
    }
    
    /**
     * 应用当前主题到当前显示的Fragment
     */
    private fun applyThemeToCurrentFragment() {
        try {
            val currentTheme = ThemeManager.getCurrentTheme(this)
            val contentFrame = findViewById<View>(R.id.content_frame)
            
            contentFrame?.let { fragmentView ->
                // 应用按钮主题到Fragment中的所有按钮
                ButtonThemeManager.updateAllButtonsInView(fragmentView, currentTheme, this)
                
                // 应用其他主题元素
                DynamicThemeUpdater.updateViewTheme(fragmentView, currentTheme, this)

            }
        } catch (e: Exception) {
            android.util.Log.w("SystemConfigActivity", 
                "Failed to apply theme to fragment: ${e.message}")
        }
    }
    
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            android.R.id.home -> {
                if (isMiniNavMode) {
                    // 迷你模式下，点击汉堡菜单恢复完整导航栏
                    restoreFullNavigationBar()
                } else {
                    // 正常模式下，打开或关闭抽屉式导航
                    if (binding.drawerLayout.isDrawerOpen(binding.navigationContainer)) {
                        binding.drawerLayout.closeDrawer(binding.navigationContainer)
                    } else {
                        binding.drawerLayout.openDrawer(binding.navigationContainer)
                    }
                }
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
    
    /**
     * 应用保存的主题
     */
    private fun applyTheme() {
        lifecycleScope.launch {
            try {
                val theme = withContext(Dispatchers.IO) {
                    ThemeManager.loadThemeFromDatabase(this@SystemConfigActivity)
                }
                withContext(Dispatchers.Main) {
                    ThemeManager.applyTheme(this@SystemConfigActivity, theme)
                    // 确保工具栏图标为白色（仅在binding已初始化时）
                    if (::binding.isInitialized) {
                        updateToolbarIconColor()
                        // 刷新迷你导航栏以应用新主题颜色
                        refreshMiniNavigationBar()
                    }
                }
            } catch (e: Exception) {
                // 如果加载失败，使用默认主题
                val defaultTheme = ThemeManager.getCurrentTheme(this@SystemConfigActivity)
                ThemeManager.applyTheme(this@SystemConfigActivity, defaultTheme)
                // 确保工具栏图标为白色（仅在binding已初始化时）
                if (::binding.isInitialized) {
                    updateToolbarIconColor()
                    // 刷新迷你导航栏以应用默认主题颜色
                    refreshMiniNavigationBar()
                }
            }
        }
    }
    
    /**
     * 刷新迷你导航栏以应用新主题
     */
    private fun refreshMiniNavigationBar() {
        if (isMiniNavMode) {
            // 获取当前选中的菜单项
            val selectedMenuId = binding.navigationView.checkedItem?.itemId ?: R.id.nav_home_config
            // 清除现有内容并重新构建
            binding.miniNavContainer.removeAllViews()
            populateMiniNavigationBar(selectedMenuId)
        }
    }
    
    /**
     * 切换到迷你导航栏模式（仅显示图标）
     */
    private fun switchToMiniNavMode(selectedMenuId: Int) {
        if (!isMiniNavMode) {
            isMiniNavMode = true
            showMiniNavigationBar(selectedMenuId)
        }
        binding.drawerLayout.closeDrawer(binding.navigationContainer)
    }
    
    /**
     * 显示迷你导航栏
     */
    private fun showMiniNavigationBar(selectedMenuId: Int) {
        // 清空迷你导航栏容器
        binding.miniNavContainer.removeAllViews()
        
        // 设置迷你导航栏宽度并显示
        val layoutParams = binding.miniNavContainer.layoutParams
        layoutParams.width = (80 * resources.displayMetrics.density).toInt() // 80dp
        binding.miniNavContainer.layoutParams = layoutParams
        binding.miniNavContainer.visibility = View.VISIBLE
        
        // 应用主题背景色
        applyMiniNavTheme()
        
        // 创建菜单图标按钮
        populateMiniNavigationBar(selectedMenuId)
    }
    
    /**
     * 恢复完整导航栏
     */
    private fun restoreFullNavigationBar() {
        if (isMiniNavMode) {
            isMiniNavMode = false
            
            // 隐藏迷你导航栏
            binding.miniNavContainer.visibility = View.GONE
            
            // 打开完整导航栏
            binding.drawerLayout.openDrawer(binding.navigationContainer)
        }
    }
    
    /**
     * 应用迷你导航栏主题
     */
    private fun applyMiniNavTheme() {
        val currentTheme = ThemeManager.getCurrentTheme(this)
        val themeColors = NavigationThemeManager.getNavigationThemeColors(currentTheme, this)
        
        // 设置迷你导航栏背景色
        binding.miniNavContainer.setBackgroundColor(themeColors.drawerBackground)
    }
    
    /**
     * 填充迷你导航栏内容
     */
    private fun populateMiniNavigationBar(selectedMenuId: Int) {
        // 获取当前主题颜色
        val currentTheme = ThemeManager.getCurrentTheme(this)
        val themeColors = NavigationThemeManager.getNavigationThemeColors(currentTheme, this)
        
        // 创建菜单图标按钮
        menuIconMap.forEach { (menuId, iconRes) ->
            val iconButton = android.widget.ImageButton(this).apply {
                setImageResource(iconRes)
                layoutParams = android.widget.LinearLayout.LayoutParams(
                    (56 * resources.displayMetrics.density).toInt(), // 56dp
                    (56 * resources.displayMetrics.density).toInt() // 56dp
                ).apply {
                    setMargins(
                        (12 * resources.displayMetrics.density).toInt(), // 12dp
                        (8 * resources.displayMetrics.density).toInt(),  // 8dp
                        (12 * resources.displayMetrics.density).toInt(), // 12dp
                        (8 * resources.displayMetrics.density).toInt()   // 8dp
                    )
                }
                background = if (menuId == selectedMenuId) {
                    // 选中状态背景 - 使用主题颜色
                    android.graphics.drawable.GradientDrawable().apply {
                        shape = android.graphics.drawable.GradientDrawable.RECTANGLE
                        cornerRadius = 12f
                        // 使用主题色的半透明版本作为背景
                        setColor((themeColors.primaryColor and 0x00FFFFFF) or 0x2D000000)
                        setStroke(2, themeColors.primaryColor)
                    }
                } else {
                    // 未选中状态背景
                    android.graphics.drawable.GradientDrawable().apply {
                        shape = android.graphics.drawable.GradientDrawable.RECTANGLE
                        cornerRadius = 12f
                        setColor(android.graphics.Color.TRANSPARENT)
                    }
                }
                imageTintList = if (menuId == selectedMenuId) {
                    // 选中状态：使用白色图标，提供更好的对比度
                    android.content.res.ColorStateList.valueOf(android.graphics.Color.WHITE)
                } else {
                    // 未选中状态：使用主题图标颜色
                    android.content.res.ColorStateList.valueOf(themeColors.iconColor)
                }
                scaleType = android.widget.ImageView.ScaleType.CENTER_INSIDE
                elevation = 4f
                
                // 设置点击事件
                setOnClickListener {
                    handleMiniNavItemClick(menuId)
                }
            }
            binding.miniNavContainer.addView(iconButton)
        }
        
        // 添加底部间距
        val bottomSpacer = android.view.View(this).apply {
            layoutParams = android.widget.LinearLayout.LayoutParams(
                android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
                0,
                1f // 占据剩余空间
            )
        }
        binding.miniNavContainer.addView(bottomSpacer)
        
        // 添加底部返回按钮
        val backButton = android.widget.ImageButton(this).apply {
            setImageResource(R.drawable.ic_home_configuration)
            layoutParams = android.widget.LinearLayout.LayoutParams(
                (56 * resources.displayMetrics.density).toInt(), // 56dp
                (56 * resources.displayMetrics.density).toInt() // 56dp
            ).apply {
                setMargins(
                    (12 * resources.displayMetrics.density).toInt(), // 12dp
                    (16 * resources.displayMetrics.density).toInt(), // 16dp
                    (12 * resources.displayMetrics.density).toInt(), // 12dp
                    (24 * resources.displayMetrics.density).toInt()  // 24dp
                )
            }
            background = android.graphics.drawable.GradientDrawable().apply {
                shape = android.graphics.drawable.GradientDrawable.RECTANGLE
                cornerRadius = 12f
                setColor(themeColors.primaryColor) // 使用主题主色
            }
            imageTintList = android.content.res.ColorStateList.valueOf(
                themeColors.buttonTextColor // 使用主题按钮文字颜色
            )
            scaleType = android.widget.ImageView.ScaleType.CENTER_INSIDE
            elevation = 4f
            
            setOnClickListener {
                finish() // 返回首页
            }
        }
        binding.miniNavContainer.addView(backButton)
    }
    
    /**
     * 处理迷你导航栏项目点击
     */
    private fun handleMiniNavItemClick(menuId: Int) {
        when (menuId) {
            R.id.nav_home_config -> {
                showFragment(HomeConfigFragment())
                updateToolbarTitle(R.id.nav_home_config)
            }
            R.id.nav_network_config -> {
                showFragment(NetworkConfigFragment())
                updateToolbarTitle(R.id.nav_network_config)
            }
            R.id.nav_serial_config -> {
                showFragment(SerialConfigFragment())
                updateToolbarTitle(R.id.nav_serial_config)
            }
            R.id.nav_face_recognition -> {
                showFragment(FaceRecognitionFragment())
                updateToolbarTitle(R.id.nav_face_recognition)
            }
            R.id.nav_feature_library -> {
                showFragment(FeatureLibraryFragment())
                updateToolbarTitle(R.id.nav_feature_library)
            }
            R.id.nav_password_management -> {
                showFragment(PasswordManagementFragment())
                updateToolbarTitle(R.id.nav_password_management)
            }
            R.id.nav_user_management -> {
                showFragment(UserManagementFragment())
                updateToolbarTitle(R.id.nav_user_management)
            }
            R.id.nav_card_management -> {
                showFragment(CardManagementFragment())
                updateToolbarTitle(R.id.nav_card_management)
            }
            R.id.nav_operation_log -> {
                showFragment(OperationLogFragment())
                updateToolbarTitle(R.id.nav_operation_log)
            }
            R.id.nav_usage_record -> {
                showFragment(UsageRecordFragment())
                updateToolbarTitle(R.id.nav_usage_record)
            }
            R.id.nav_program_management -> {
                showFragment(ProgramManagementFragment())
                updateToolbarTitle(R.id.nav_program_management)
            }
        }
        
        // 重新填充迷你导航栏以更新选中状态
        binding.miniNavContainer.removeAllViews()
        populateMiniNavigationBar(menuId)
    }
} 